package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dto.PageResponseResult;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.NewsAuthDTO;
import com.heima.model.wemedia.dto.WmNewsDTO;
import com.heima.model.wemedia.dto.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojo.*;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        // 校验参数   分页参数  是否登录
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 封装查询条件
        LambdaQueryWrapper<WmNews> lambdaQuery = Wrappers.<WmNews>lambdaQuery();
        // 标题
        /*if(StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQuery.like(WmNews::getTitle,dto.getKeyword());*/
        lambdaQuery.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //  频道  eq  比较
        lambdaQuery.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 状态
        lambdaQuery.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //开始时间  结束时间  between  范围之间
        lambdaQuery.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        // 登录用户
        lambdaQuery.eq(WmNews::getUserId, user.getId());
        //设置创建时间降序
        lambdaQuery.orderByDesc(WmNews::getCreatedTime);
        // 封装分页条件
        Page<WmNews> pageResult = new Page<>(dto.getPage(), dto.getSize());
        // 执行查询
        IPage<WmNews> page = this.page(pageResult, lambdaQuery);
        // 返回结果  Records:获取所有数据记录
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        // 设置图片前缀路径
        result.setHost(webSite);
        return result;
    }

    /**
     * // 自媒体文章-发布-修改-保存
     *
     * @param dto 对象
     * @return
     */
    @Autowired
    RabbitTemplate rabbitTemplate;

   // @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {

        // 1 检查参数  封装WmNews对象
        WmNews wmNews = parseDtoToWmnews(dto);
        //2 保存或修改文章
        saveOrUpdateWmNews(wmNews);

        //3 保存  文章内容或封面 和素材的关联关系
        //  TODO:从文章你内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());

        //  TODO:保存文章内容引用素材的关联关系
        saveRelativeInfo(materialUrls, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
        //  TODO:保存封面引用素材的关联关系
        saveRelativeInfoForCover(materialUrls, wmNews, dto);
        // TODO:发表发送MQ消息  触发异步自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送文章自动审核消息    目的队列:{}  文章id:{}" + NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 自媒体文章  根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章  根据id删除文章
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 自媒体文章   文章上下架功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));


        // 下架消息
        if (WemediaConstants.WM_NEWS_DOWN.equals(enable)) {
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发布文章   下架消息  文   章id:{}" + wmNews.getArticleId());
        } else {
            // 上架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发布文章   上架消息  文章id:{}" + wmNews.getArticleId());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存文章封面和素材的关联关系
     *
     * @param materialUrls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {
        // 前端传来的封面集合  有前缀  查不到
        List<String> images = dto.getImages();
        //        判断前端传入type是否为-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 需要自动生成封面  规则
            int size = materialUrls.size();
            if (size == 0) {
                //  内容中没有图片 则为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                //         - 内容图片的个数小于等于2  则为单图截图一张图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {
                //         - 内容图片大于2  则为多图  截图三张图
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imagesToStr(images));
            }
            // 修改文章
            this.updateById(wmNews);
        }
        // 前端传来的封面集合  有前缀   images传进来 查不到
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            // 调用保存关联关系方法
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);

        }

    }

    /**
     * 保存素材和文章关联关系方法
     *
     * @param materialUrls 素材的路径list
     * @param wmNews       文章
     * @param type         引用类型 0 内容引用   1 封面引用
     */
    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        // 先根据素材路径集合  查询素材表  得到对应的id集合
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        // 素材id
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        // 路径条件
                        .in(WmMaterial::getUrl, materialUrls)
                        // 只返回ID字段值
                        .select(WmMaterial::getId)
        );
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        //  判断id集合的数量  是否 等于 素材路径集合的数量   不等于 提示素材缺失
        if (ids.size() < materialUrls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失");
        }
        //  批量的插入关联关系
        for (WmMaterial wmMaterial : wmMaterials) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd((short)0);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
        wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), type);

    }



    /**
     * 提取出内容中 所涉及的素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {

        List<Map> mapList = JSON.parseArray(content, Map.class);
        // 创建流
        return mapList.stream()
                // 集合中 找到所有type 为image的map
                .filter(x -> "image".equals(x.get("type")))
                //获取map的value字段值  得到路径
                .map(x -> String.valueOf(x.get("value")))
                //替换掉路径的前缀
                .map(url -> url.replaceAll(webSite, ""))
                //去除重复的素材
                .distinct()
                // 将得到的素材返回给路径集合
                .collect(Collectors.toList());

    }

    // 1 检查参数  封装WmNews对象
    private WmNews parseDtoToWmnews(WmNewsDTO dto) {
        // 检查内容  标题  是否登录
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章的标题和内容不能为空");
        }
        // 当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录 ");
        }
        // dto拷贝属性Wmnews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // type 如果type为-1  暂时将Wmnews 中的type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // dto中的images式list  Wmnews的images是字符串
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            wmNews.setImages(imagesToStr(dto.getImages()));
        }
        // 补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * 将字符串集合  转为  字符串用逗号拼接
     *
     * @param images [url1.jpg,url2.jpg]
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream() // 创建流对象
                // 替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite, ""))
                // 将字符串 使用逗号拼接
                .collect(Collectors.joining(","));
    }

    //2 保存或修改文章
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //  Wmnews 信息补全(创建时间  上下架  发表用户id)
        wmNews.setCreatedTime(new Date());
        // 文章状态 9
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //  判断id是否为空  为空保存Wmnews
        if (wmNews.getId() == null) {
            // 为空保存wmnews
            boolean save = this.save(wmNews);

        } else {
            //  如果不为空  修改wmnews  修改前要先将 文章和素材的关联关系删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }

    }

    @Autowired
    WmNewsMapper wmNewsMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        // 检查参数
        dto.checkParam();
        // 记录当前页
        Integer currentPage = dto.getPage();
        // 设置起始页
//        dto.setPage(dto.getPage() - 1 * dto.getSize());
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        // 分页查询
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        // 统计多少条的书记
        long listCount = wmNewsMapper.findListCount(dto);
        // 结果返回
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), listCount, listAndPage);
        // 自动填充
        result.setHost(webSite);
        return result;
    }


    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //  TODO:通知定时发布文章
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)) {
            // 获取发布时间
            long time = wmNews.getPublishTime().getTime();
            // 获取当前时间
            long timeMillis = System.currentTimeMillis();
            // 距离发布时间 = 发布时间 - 当前时间
            long newTime = time - timeMillis;
            // 发送消息 并设置消息  x-delay  距离发布时间
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        /**
                         * 消息后置处理器   用于改变消息属性
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties()
                                    // 延迟属性   延迟时间是多少
                                    .setHeader("x-delay", newTime <= 0 ? 0 : newTime);
                            return message;
                        }
                    }
            );
            log.info("成功发送文章待发布消息  文章id:{}   延迟时间:{}", wmNews.getId(), newTime);
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}







